# -*- coding: utf-8 -*-
import subprocess
import time
import logging
import argparse

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
logger = logging


class ApplicationOperate:
    def __init__(self, **kwargs):
        # 用于记录已评论的内容
        self.used_comments = []
        self.screen_width = None
        self.screen_height = None
        self.package_names = [name.strip() for name in
                              kwargs.get("packageName").replace("\\n", "\n").split('\n')]  # 支持多个包名
        self.deviceName = kwargs.get("deviceName")
        self.appium_url = kwargs.get("appium_url")
        self.platformVersion = kwargs.get("platformVersion")
        self.systemPort = kwargs.get("systemPort")
        self.adbPort = kwargs.get("adbPort")

        self.driver = None
        self.max_retries = 1
        self.failure_count = 0

    def run(self):
        while self.max_retries > 0:
            try:
                time.sleep(3)
                logger.info("开始执行应用权限设置任务...")
                self.script()
                break
            except Exception as e:
                logger.error(f"发生异常: {e}")
                self.failure_count += 1
                self.max_retries -= 1
                if self.max_retries == 0:
                    raise Exception("任务失败")
        logger.info("任务结束")

    @staticmethod
    def execute_adb_command(adb_command):
        """
        执行单条 ADB 命令

        :param adb_command: 完整的 ADB 命令字符串
        :return: 命令执行结果（stdout）
        """
        try:
            logger.info(f"执行 ADB 命令: {adb_command}")
            result = subprocess.run(
                adb_command,
                shell=True,
                check=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
            logger.info(f"命令执行成功: {adb_command}")
            return result.stdout.decode('utf-8')
        except subprocess.CalledProcessError as e:
            error_msg = e.stderr.decode('utf-8')
            # 如果是权限未声明的安全异常，则只记录警告而不是错误
            if "has not requested permission" in error_msg and "Security exception" in error_msg:
                logger.warning(f"权限未声明，跳过命令: {adb_command}")
                # logger.warning(f"警告信息: {error_msg}")
            else:
                logger.error(f"命令执行失败: {adb_command}")
                logger.error(f"错误信息: {error_msg}")

    def initialize_device_settings(self):
        """
        执行设备初始化所需的 ADB 命令
        """
        logger.info("开始初始化设备设置")

        permissions = [
            # 应用存储的读取权限
            "android.permission.READ_EXTERNAL_STORAGE",
            # 应用存储的写入权限
            "android.permission.WRITE_EXTERNAL_STORAGE",
            # 应用的电话权限
            "android.permission.READ_PHONE_STATE",
            # 定位权限
            "android.permission.ACCESS_COARSE_LOCATION",
            # 相机权限
            "android.permission.CAMERA",
            # 录音权限
            "android.permission.RECORD_AUDIO",
            # 通讯录权限
            "android.permission.READ_CONTACTS",
            # 短信权限
            "android.permission.READ_SMS",
            # 日历权限
            "android.permission.READ_CALENDAR",
            # 写入日历权限
            "android.permission.WRITE_CALENDAR",
        ]

        for package_name in self.package_names:  # 遍历每个包名
            for permission in permissions:
                # 使用 \n 进行换行控制（如果需要）
                cmd = f"adb -s {self.deviceName} -P {self.adbPort} shell pm grant {package_name} {permission}"
                try:
                    self.execute_adb_command(cmd)
                except Exception as e:
                    logger.error(f"执行命令失败: {cmd}")
                    logger.error(f"错误详情: {e}")

    def script(self):
        """
        主脚本流程，处理多个链接并进行重试机制
        """
        self.initialize_device_settings()

        logger.info("所有链接处理完成")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-j', '--job_id', dest='job_id', type=str, default=None, required=True, help='target job_id')
    parser.add_argument('-u', '--appium_url', dest='appium_url', type=str, default=None, help='target appium_url')
    parser.add_argument('-d', '--deviceName', dest='deviceName', type=str, default=None, help='target deviceName')
    parser.add_argument('-s', '--systemPort', dest='systemPort', type=str, default=None, help='target systemPort')
    parser.add_argument('-a', '--adbPort', dest='adbPort', type=str, default=None, help='target adbPort')
    parser.add_argument('-p', '--platformName', dest='platformName', type=str, default=None, help='target platformName')
    parser.add_argument('-ver', '--platformVersion', dest='platformVersion', type=str, default=None,
                        help='target platformVersion')
    parser.add_argument('-v', '--variables', dest='variables', type=str, default='{}', help='target variables')
    #
    parser.add_argument('-packageName', '--packageName', type=str, required=True)

    args = parser.parse_args()
    ApplicationOperate(**vars(args)).run()
